package com.tuo51.manager.controller;


import com.tuo51.evaluate.domain.evaluatingV2.EvaluateV2Record;
import com.tuo51.core.domain.staffs.Staff;
import com.tuo51.evaluate.repositories.evaluatev2.EvaluateV2RecordRepository;
import com.tuo51.evaluate.service.EvaluateV2ExportService;
import com.tuo51.evaluate.service.EvaluateV2Service;
import com.tuo51.core.service.StaffService;
import com.tuo51.evaluate.vo.evaluate.EvaluateV2RecordVO;
import com.tuo51.foudation.constant.RequestConstant;
import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.model.MemVerificationCache;
import com.tuo51.foudation.model.StatusResponse;
import com.tuo51.foudation.utils.QrCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.HashMap;
import java.util.Map;

import static com.tuo51.foudation.constant.RequestConstant.TICKET;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * 报告列表
 */
@RestController
@RequestMapping("/mapi/pb_reports")
@Api(value = "/mapi/pb_reports", tags = "OP - 儿心量表报告管理")
public class MAPIPbReportsController {
    @Value("${export.pb.share_url_ma}")
    private String exportShareURLMA;

    @Autowired
    EvaluateV2RecordRepository recordRepository;

    @Autowired
    EvaluateV2Service evaluateService;

    @Autowired
    StaffService staffService;

    @Autowired
    EvaluateV2ExportService exportService;

    @Autowired
    MemVerificationCache cache;

    @RequestMapping(value = "/list", method = GET)
    @ApiOperation(value = "资源列表")
    public StatusResponse list(@RequestHeader(TICKET) String ticket,
                               @RequestParam(value = "pageNum", required = false, defaultValue = "0")Integer pageNum,
                               @RequestParam(value = "pageSize", required = false, defaultValue = "15")Integer pageSize,
                               @RequestParam(value = "orderBy", required = false)String orderBy,
                               @RequestParam(value = "searchBy", required = false) String searchBy){

        cache.getStaffId(ticket);

        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);

        Page<EvaluateV2RecordVO> ret = recordRepository.findAll(new Specification<EvaluateV2Record>() {
            @Override
            public Predicate toPredicate(Root<EvaluateV2Record> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

                Predicate base = cb.isFalse(root.get("deleted"));

                if (StringUtils.isNotEmpty(searchBy)){
                    String key = "%" + searchBy + "%";
                    Predicate p = cb.or(cb.like(root.get("childrenName"), key),
                            cb.like(root.get("createTeacherName"), key),
                            cb.like(root.get("evaluatingTeacherName"), key));
                    base = cb.and(base, p);
                }

                query.where(base);

                if (StringUtils.isNotEmpty(orderBy)){
                    query.orderBy(cb.asc(root.get(orderBy)));
                }else {
                    query.orderBy(cb.desc(root.get("created")));
                }

                return query.getRestriction();
            }
        }, pageRequest).map(k->EvaluateV2RecordVO.of(k));

        return StatusResponse.success(ret);
    }

    /**
     * 推送到家长时间轴
     *
     * @param evaluateRecordId 测评纪录id
     * @return
     */
    @ApiOperation(value = "推送给家长",httpMethod = "POST")
    @RequestMapping(value = "/grant_parent")
    public StatusResponse grantParentEvaluate(@RequestHeader(TICKET) String ticket, String evaluateRecordId) {

        String staffId = cache.getStaffId(ticket);

        EvaluateV2Record record = evaluateService.getEvaluateDetail(evaluateRecordId);
        if(record == null){
            throw  new BusinessException(ErrorCode.EVALUATE_RECORD_NOT_EXIST, "报告不存在");
        }

        if(record.getParentGranted()){
            throw new BusinessException(ErrorCode.VERSION_ERROR, "已经推送给家长了");
        }

        Staff sourceTeacher = staffService.getById(record.getEvaluatingTeacherId());
        evaluateService.grantEvaluateToParent(sourceTeacher, record);

        return StatusResponse.success(true);
    }

    /**
     * 推送到家长时间轴
     *
     * @param evaluateRecordId 测评纪录id
     * @return
     */
    @ApiOperation(value = "取消推送给家长",httpMethod = "POST")
    @RequestMapping(value = "/revoke_grant_parent")
    public StatusResponse revokeGrantParent(@RequestHeader(TICKET) String ticket, String evaluateRecordId) {

        String staffId = cache.getStaffId(ticket);

        EvaluateV2Record record = evaluateService.getEvaluateDetail(evaluateRecordId);
        if(record == null){
            throw  new BusinessException(ErrorCode.EVALUATE_RECORD_NOT_EXIST, "报告不存在");
        }

        evaluateService.revokeGrantEvaluateToParent(record.getEvaluatingTeacherId(), record);

        return StatusResponse.success();
    }

    @ApiOperation(value = "支付测评",httpMethod = "POST")
    @RequestMapping(value = "/pay_record")
    public StatusResponse payEvaluateRecord(@RequestHeader(TICKET) String ticket, String evaluateRecordId) {
        String staffId = cache.getStaffId(ticket);

        EvaluateV2Record evaluateRecord = evaluateService.payEvaluate(evaluateRecordId);

        return StatusResponse.success(evaluateRecord);
    }


    @ApiOperation(value = "预览",httpMethod = "GET")
    @RequestMapping(value = "/preview_url")
    public StatusResponse previewReport(@RequestHeader(RequestConstant.TICKET) String ticket,
                                        String evaluateRecordId) {
        String staffId = cache.getStaffId(ticket);

        EvaluateV2Record evaluateRecord = evaluateService.getEvaluateDetail(evaluateRecordId);

        String url = exportShareURLMA + "?id=" + evaluateRecord.getId();

        Map result = new HashMap();

        result.put("url", url);
        result.put("childrenName", evaluateRecord.getChildrenName());
        result.put("month", evaluateRecord.getMonth());

        try {
            String iconName = "basicprofile.png";

            String base64EncodedQRCodeImg = QrCodeUtils.base64EncodedQRCode(url, iconName, false );
            result.put("qrcode", "data:image/png;base64," + base64EncodedQRCodeImg);

        } catch (Exception e) {
            e.printStackTrace();
            return StatusResponse.error(ErrorCode.ERROR, "预期之外的错误");
        }

        return StatusResponse.success(result);
    }

    @ApiOperation(value = "导出word报告",httpMethod = "GET")
    @RequestMapping(value = "/export")
    public StatusResponse exportReport(@RequestHeader(RequestConstant.TICKET) String ticket,
                                       String evaluateRecordId) {
        String staffId = cache.getStaffId(ticket);

        EvaluateV2Record evaluateRecord = evaluateService.getEvaluateDetail(evaluateRecordId);

        if (evaluateRecord == null){
            throw new BusinessException(ErrorCode.EVALUATE_RECORD_NOT_EXIST, "测评报告不存在");
        }

        //导出
        Staff staff = staffService.getById(evaluateRecord.getEvaluatingTeacherId());
        String exported_file = exportService.exportEvaluateWordReportToOSS(null, evaluateRecordId, staff, true);

        return StatusResponse.success(exported_file);
    }
}
